<template>
  <view>
    <view class="home_detail">
      <uni-list>
        <uni-list-item title="门店名称">
          <template slot="footer">
            <input  v-model:value="storeName" placeholder="请输入门店名称" style="text-align:right;font-size: 32rpx;" />
          </template>
        </uni-list-item>
        <uni-list-item title="门店位置" link :rightText="storeAddress!=''?storeAddress:'设定位置'"
          @tap="gotolay">
          </uni-list-item>
          <uni-list-item title="分类管理" link :rightText="typeCount!=''?typeCount+'个分类':''">
          </uni-list-item>
          <uni-list-item title="设备管理" link :rightText="deviceCount!=''?deviceCount+'台设备':''" @tap="gotoDeviceList(storeId)">
          </uni-list-item>
      </uni-list>
      <view class="home_user">门店成员</view>
    </view>
    <scroll-view scroll-y="true" :style="'height:'+ clientHeight+'px;'">
      <uni-list v-for="(item,index) in userList" :key="index">
        <uni-list-item :title="item.nickName" :note="item.phonenumber" showArrow
          :thumb="item.avatar==null||item.avatar==''?avatar:baseUrl+item.avatar" 
          thumb-size="lg" :rightText="item.isadmin==1?'管理员':''" @tap="setStoreUser(item.equipmentStoreNo,item.isadmin,item.userId)"></uni-list-item>
      </uni-list>
    </scroll-view>
    <view class="btn_baocun" style="margin-top: 30rpx;min-height: 180rpx;">
      <button class="add_user" v-if="isAdmin==1"  open-type="share" type="primary">
        <uni-icons type="plusempty" size="20"></uni-icons>
        <text>添加门店成员</text>
      </button>
      <button type="warn"  v-if="isAdmin==1" @tap="removeStore" style="width: 80%;background-color: #ff976a;height: 80rpx;
         line-height: 80rpx;margin-top: 20rpx;">移除门店</button>
    </view>
  </view>
</template>

<script>
  import {getStore,updateStore,delStore} from '@/api/system/store/store.js'
  import {getStoreShareUsers,setAdmin,delShareRecord, setIsAdmin} from '@/api/system/store/shareRecord.js'
   import config from '@/config'
  export default {
    data() {
      return {
        storeName: "",
        storeAddress: "",
        typeCount:"",
        deviceCount:"",
        latitude: "",
        longitude: "",
        userId: uni.getStorageSync("userId"),
        queryParams: {
          equipmentStoreNo: null,
          shareType: 1
        },
        userList: [],
        storeId: '',
        isAdmin: 0,
        clientHeight: 0,
        baseUrl: config.baseUrl,
        avatar:"https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
      }
    },
    onLoad(option) {
      this.storeId=option.storeId
      this.isAdmin=option.isAdmin
      //查询门店详细
      this.getStoreDetaile()
      //查询分享用户
      this.getShareUser()
    },
    onShow() {
      var that = this;
      uni.getSystemInfo({
        success: function(res) {
          let screenHeight = uni.getSystemInfoSync().windowHeight //获取屏幕高度
          // 通过query 获取其余盒子的高度
          let query = uni.createSelectorQuery().in(that)
          query.select(".home_detail").boundingClientRect()
          query.select(".btn_baocun").boundingClientRect()
          //通过query.exec返回的数组 进行减法 同时 去除margin 和border的
          query.exec(res => {
            let h1 = res[0].height
            let h2 = res[1].height
            let scrollHeight = screenHeight - h1 - h2 -90
            that.clientHeight = scrollHeight
          })
        }
      })
    },
    methods: {
      //查询们的详细
      getStoreDetaile(){
        getStore(this.storeId).then(response => {
           if(response.code==200){
            let maps = new Map();
            this.storeName = response.data.storeName;
            this.storeAddress = response.data.storeAddress
            this.deviceCount =response.data.mkEquipments.length
            this.latitude = response.data.lat
            this.longitude = response.data.lon
            //获取类型数量去重
            this.typeCount=(response.data.mkEquipments.map(itme=>({
              id:parseInt(itme.equipmentTypeId),
              name:itme.mkEquipmentType.equipmentTypeName
            })).filter((v)=>!maps.has(v.id)&& maps.set(v.id,1))).length
           }
        })
      },
      //查询分享的门店成员包括自己
      getShareUser(){
        this.queryParams.equipmentStoreNo=this.storeId
        getStoreShareUsers(this.queryParams).then(response => {
          if(response.code == 200){
            this.userList=response.rows
            uni.stopPullDownRefresh()
          }
        })
      },
      //设定位置方法
      gotolay() {
        //弹窗定位让其选择，成功后把地址和名称一起赋值给地址字段
        uni.chooseLocation({
          success: res => {
            this.storeAddress = res.name
            this.latitude = res.latitude
            this.longitude = res.latitude
          },
          fail: err => {
            this.$modal.msgError(err);
          }
        })
      },
      //跳转设备列表
      gotoDeviceList(storeId){
        this.$tab.navigateTo("/devicelistpkg/deviceManage/deviceList?storeId="+storeId)
      },
      //设置管理员或删除门店成员
    setStoreUser(equipmentStoreNo,isadmin,userId) {
      if(this.isAdmin==1){
        if(userId!=this.userId){
          var thant = this;
          uni.showActionSheet({
            alertText: "请选择",
            itemList: [isadmin==1?'设置为普通成员':'设置为管理员', '删除'],
            success: (res) => {
              switch (res.tapIndex) {
                case 0:
                  uni.showModal({
                    title: '提示',
                    content: isadmin==1?'确定设置该成员为普通成员吗？':'确定设置该成员为管理员吗？',
                    success: function(res) {
                      if (res.confirm) {
                        try {
                          const data={
                            equipmentStoreNo:equipmentStoreNo,
                            isadmin:isadmin==1?0:1,
                            recipientId:userId
                          } 
                          setIsAdmin(data).then(response => {
                            if(response.code == 200){
                               uni.showToast({
                                 title: '设置成功',
                                 duration: 1500,
                                 success: function() {
                                   //查询门店成员
                                   thant.getShareUser()
                                 }
                               })
                            }
                          })
                        } catch (err) {
                          thant.$modal.msgError(err.msg);
                        }
                      }
                    }
                  })
                  break;
                case 1:
                  uni.showModal({
                    title: '提示',
                    content: '确定删除该门店成员吗？',
                    success: function(res) {
                      if (res.confirm) {
                        try {
                          const data={
                            equipmentStoreNo:equipmentStoreNo,
                            recipientId:userId
                          } 
                          delShareRecord(data).then(response => {
                            if(response.code == 200){
                               uni.showToast({
                                 title: '删除成功',
                                 duration: 1500,
                                 success: function() {
                                   //查询门店成员
                                   thant.getShareUser()
                                 }
                               })
                            }
                          })
                        } catch (err) {
                          thant.$modal.msgError(err.msg);
                        }
                      }
                    }
                  })
                  break;
              }
            },
            fail(error) {
              thant.$modal.msgError(error);
            }
          })
        }else{
           this.$modal.showToast("分享者本人不能设置和删除自己");
        }
        }else{
            this.$modal.msgError("暂无权限");
        }
      },
      //移除门店
      removeStore(){
        var thant = this;
        uni.showModal({
            title: '确定删除该门店吗？',
            content: '门店删除后，所有成员会被删除、门店下的分类被清空、已添加设备被解绑和重置',
            success: function(res) {
              if (res.confirm) {
                try {
                  delStore(thant.storeId).then(response => {
                    if (response.code == 200) {
                     uni.navigateTo({
                       url: '/devicelistpkg/storeManage/storeList',
                       success: (res) => {
                         if (res.errMsg = "navigateTo:ok") {
                           thant.$modal.msgSuccess("删除成功");
                         }
                       },
                     })
                    }
                  })
                } catch (err) {
                  thant.$modal.msgError(err.msg);
                }
              }
            }
        })
      },
    },
    onUnload() {
      try {
        const data={
          storeId:this.storeId,
          storeName: this.storeName,
          storeAddress: this.storeAddress,
          lat: this.latitude,
          lon: this.longitude
        }
      updateStore(data).then(response => {
        if (response.code==200) {
        this.$modal.msgSuccess("修改成功")
        }else{
          this.$modal.msgError("修改失败")
        }
        })
      } catch (err) {
        this.$modal.msgError(err)
      }
    },
    //下拉刷新
    onPullDownRefresh() {
      this.getShareUser()
    },
    //分享门店成员
    onShareAppMessage() {
           return {
                 title: '和我一起加入门店',
                 path: '/pages/shareConfirm/index?equipmentStoreNo='+this.storeId+'&shareType=1&sharerId='+this.userId,
                 imageUrl: 'https://mkservice.mk-iot.com/subFile/mk2240/LOGO.png'
           }
       }
  }
</script>

<style>
  page {
    background-color: #f9f9f9;
  }

  .home_detail {
    margin-top: 56rpx;
    width: 92%;
    margin: 56rpx auto;
  }

  ::v-deep .home_detail .uni-list-item__extra-text {
    font-size: 32rpx;
    overflow: hidden;
    text-align: right;
    vertical-align: middle;
    width: 300rpx;
  }

  .home_user {
    margin: 30rpx 0 30rpx 30rpx;
    font-size: 28rpx;
    color: #acacac;
  }
  .add_user{
    width: 80%;height: 80rpx;line-height: 80rpx;
  }
</style>